<script setup lang='ts' name="protocol-management-list">
import ExpandBtn from '@/components/expand-btn.vue'
import { ArrowRight } from '@element-plus/icons-vue'
import { useJcOrderMetaAuditOrder, useJcOrderMetaCompleteOrder, useJcOrderMetaGetOne, useJcOrderMetaSubmitToAudit, useRecallReceivePendingOrder } from '@fl/api/purchase'
import { ElPagination } from 'element-plus'
import { ref, toRefs } from 'vue'
import { useRouter } from 'vue-router'

import AuditOrder from '../../protocol-management/component/audit-order.vue'
import IsAudit from '../../protocol-management/component/is-audit.vue'
import { ORDERSTATUS_DICT } from '../constant'
import ExpandRow from './expand.vue'

const props = withDefaults(defineProps<{
    data?: any
    loading?: boolean
    total?: any
}>(), {
    data: () => [],
    loading: false,
    total: 0,
})
const emits = defineEmits(['doAction', 'pageChange'])
const { push } = useRouter()
const { isPending: submitLoading, mutate: submitMutate } = useJcOrderMetaSubmitToAudit()

const { isPending: auditOrderLoading, mutate: auditOrderMutate } = useJcOrderMetaAuditOrder()

const { isPending: closeLoading, mutate: closeMutate } = useRecallReceivePendingOrder()

const { isPending: completeLoading, mutate: completeMutate } = useJcOrderMetaCompleteOrder()

const { mutate: orderInfoMutate } = useJcOrderMetaGetOne()

const childIsAudit = ref<InstanceType<typeof IsAudit> | null>(null)
const childAuditOrder = ref<InstanceType<typeof AuditOrder> | null>(null)

const { data, loading, total } = toRefs(props)

const state = {
    page: 1,
    size: 10,
}

const pages = ref({ ...state })

const isAuditVisible = ref(false)
const auditOrderVisible = ref(false)

function doAction(item: any, row: any) {
    emits('doAction', item, row)
}

function handleSizeChange(val: any) {
    console.log('size', val)
    pageChange()
}
function handleCurrentChange(val: any) {
    console.log('page', val)
    pageChange()
}

function pageChange() {
    emits('pageChange', { ...pages.value })
}
function showSubmitOrder(item: any) {
    return item.orderStatus === 1 && item.buyerOperable === 1
}
const submitId = ref('')
function submitOrder(row: any) {
    submitId.value = row.id
    isAuditVisible.value = true
}

function isAuditSubmit(val: any) {
    orderInfoMutate(submitId.value, {
        onSuccess: (res) => {
            const params = {
                ...res,
                ...val,
                products: res.orderProductsVOS,
                submitType: 2, // 下单页面提交订单
            }
            submitMutate(params, {
                onSuccess: () => {
                    childIsAudit.value!.cancel()
                    ElMessage.success('操作成功')
                },
            })
        },
    })
}

function showAuditOrder(item: any) {
    return item.orderStatus === 2 && item.hasAuditAuth === 1
}
function auditOrder(item: any) {
    submitId.value = item.id
    auditOrderVisible.value = true
}

function auditOrderSubmit(val: any) {
    const params = {
        ...val,
        id: submitId.value,
    }
    auditOrderMutate(params, {
        onSuccess: () => {
            ElMessage.success('操作成功')
            childAuditOrder.value!.cancel()
            push('/purchase-pages/purchase-order-management/purchase-sales-order')
        },
    })
}

/*
    关闭订单接口暂无
*/
function showColseOrder(item: any) {
    return item.orderStatus === 3 && item.buyerOperable === 1
}
async function colseOrder(row: any) {
    console.log('🚀 ~ colseOrder ~ row:', row)
    closeMutate(String(row.id), {
        onSuccess: () => {
            ElMessage.success('操作成功')
        },
    })
}

// 完成订单
function showCompleteOrder(item: any) {
    return item.orderStatus === 7 && item.buyerOperable === 1
}

function completeOrder(row: any) {
    completeMutate(String(row.id), {
        onSuccess: () => {
            ElMessage.success('操作成功')
        },
    })
}

function checkChange(e: any, item: any) {
    console.log('1', e)
    console.log('2', item)
}
function showDetail(item: any) {
    push(`/purchase-pages/purchase-order-management/purchase-sales-order/${item.id}`)
}
</script>

<template>
    <el-skeleton v-if="loading"
                 :rows="5"
    />

    <div v-else>
        <template v-if="data?.length">
            <div v-for="(item, index) in data"
                 :key="index"
                 class="protocol-list"
            >
                <p class="top">
                    <span class="top-label truncate"
                          :title="item.createTime"
                    >下单时间：{{ item?.createTime }}</span>
                    &nbsp;&nbsp;

                    <span class="top-label truncate"
                          :title="item.orderNo"
                    >订单编号：{{ item.orderNo }}</span>
                    &nbsp;&nbsp;

                    <span class="top-label truncate"
                          :title="item.agreementName"
                    >合同名称：{{ item?.agreementName }}</span>
                    &nbsp;&nbsp;

                    <span class="top-label truncate"
                          :title="item.agreementCode"
                    >合同编号：{{ item?.agreementCode }}</span>
                </p>

                <div class="list-content">
                    <div class="check-col">
                        <el-checkbox v-model="item.checked"
                                     @change="checkChange($event, item)"
                        />
                    </div>

                    <div class="list-row">
                        <div class="list-col">
                            <div class="flex w-full">
                                <p class="col-title truncate max-w-130"
                                   :title="item?.orderName"
                                >
                                    {{ item?.orderName }}
                                </p>

                                <span class="col-tips cursor-pointer"
                                      @click="showDetail(item)"
                                >
                                    <el-icon>
                                        <ArrowRight />
                                    </el-icon>
                                </span>
                            </div>

                            <p class="truncate"
                               :title="item?.projectName"
                            >
                                项目：<span>{{ item?.projectName }}</span>
                            </p>

                            <p class="truncate"
                               :title="item?.partyB"
                            >
                                乙方：<span>{{ item?.partyB }}</span>
                            </p>
                        </div>

                        <div class="list-col">
                            <p>{{ ORDERSTATUS_DICT[item?.orderStatus]?.label }}</p>
                        </div>

                        <div class="list-col">
                            <p>来源：<span>{{ item?.orderSource }}</span></p>
                        </div>

                        <div class="list-col col-price">
                            <p>总价：<span>￥{{ item?.totalPrice }}元</span></p>

                            <p>共{{ item?.totalQuantity }}个商品</p>
                        </div>

                        <div class="list-col">
                            <!-- <ButtonItem :btns="btns"
                                        @btn-click="doAction($event, item)"
                            /> -->
                            <ElButton v-if="showSubmitOrder(item)"
                                      type="primary"
                                      size="small"
                                      :loading="submitLoading"
                                      @click="submitOrder(item)"
                            >
                                确认下单
                            </ElButton>

                            <ElButton v-if="showAuditOrder(item)"
                                      size="small"
                                      @click="auditOrder(item)"
                            >
                                审批
                            </ElButton>

                            <ElButton v-if="showColseOrder(item)"
                                      type="primary"
                                      size="small"
                                      :loading="closeLoading"
                                      @click="colseOrder(item)"
                            >
                                撤销订单
                            </ElButton>

                            <ElButton v-if="showCompleteOrder(item)"
                                      type="primary"
                                      size="small"
                                      :loading="completeLoading"
                                      @click="completeOrder(item)"
                            >
                                完成订单
                            </ElButton>
                        </div>
                    </div>
                </div>

                <div v-if="item?.deliveryNoteVOS && item?.deliveryNoteVOS.length"
                     class="expand-row"
                >
                    <p style="padding-left:5px;line-height: 32px;">
                        <ExpandBtn v-model="item.expand" />
                    </p>

                    <ExpandRow v-if="!item.expand"
                               :data="item?.deliveryNoteVOS"
                               @do-action="doAction($event, item)"
                    />
                </div>
            </div>
        </template>

        <div v-else
             style="text-align: center;"
        >
            暂无数据
        </div>

        <ElPagination v-model:current-page="pages.page"
                      v-model:page-size="pages.size"
                      layout="total, sizes, prev, pager, next, jumper"
                      :total="total"
                      small
                      background
                      mt-20
                      flex
                      justify-end
                      @size-change="handleSizeChange"
                      @current-change="handleCurrentChange"
        />
    </div>

    <IsAudit ref="childIsAudit"
             v-model:visible="isAuditVisible"
             v-model:loading="submitLoading"
             @submit="isAuditSubmit"
    />

    <AuditOrder ref="childAuditOrder"
                v-model:visible="auditOrderVisible"
                v-model:loading="auditOrderLoading"
                @submit="auditOrderSubmit"
    />
</template>

<style lang="less" scoped>
@bg-color: #f5f6fa;
@label-color: gray;

.col-tips {
    .el-icon {
        color: @label-color;
        border: 1px solid @label-color;
        border-radius: 8px;
        padding: 2px;
        transform: translateY(2px);
        margin-right: 10px;
        margin-left: 5px;
    }
}

.protocol-list {
    width: 100%;
    border: 1px solid @bg-color;
    border-radius: 4px;
    margin-bottom: 20px;

    .top {
        width: 100%;
        background: @bg-color;
        color: #000;
        padding-left: 20px;

        .top-label {
            display: inline-block;
            color: @label-color;
            line-height: 35px;
            width: 250px;
        }
    }

    .list-content {
        display: flex;
        align-items: center;
        width: 100%;
        padding: 10px 0;

        .check-col {
            width: 60px;
            text-align: center;
        }

        .list-row {
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .list-col {
                min-width: 200px;
                color: @label-color;
                max-width: 200px;

                .col-title {
                    font-size: 14px;
                    font-weight: 600;
                    color: #000;
                }
            }

            .col-price {
                text-align: right;

                span {
                    color: red;
                    font-size: 16px;
                    font-weight: 600;
                }
            }
        }
    }

    .expand-row {
        p {
            padding-left: 10px;
        }
    }
}
</style>
